

function websocket(server) {
    var io = require('socket.io')(server);
    var Message = require('../models/message');
	var robot = require("../db/robot");
    var users = {};
    var rooms = {};
    io.on('connection', function (socket) {
    	console.log("connection");
    	//初始化链接
    	socket.on("connectInit",function(obj){
    		this.username = obj.username;
      		users[obj.username] = this.id;
			if(obj.type == 4){
				//加入房间，进行群聊
				var key = "room"+obj.type;
				if(!rooms[key]){
					rooms[key] = key;
				}
				socket.join(key);
				global.logger.info(obj.username+"加入房间"+ key);
			}
      	});
      	
      	
    	
      //监听用户发布聊天内容
      socket.on('message', function (obj) {
			var that = this;
       		//来消息了
	       	var mess = {
	          username: obj.username,
	          receive:obj.receive,
	          type:obj.type,      //1:对客服讲话,2:对人讲话,3:系统广播,4:大厅全局聊天,5：机器人聊天
	          src:obj.src || '', 
	          img: obj.img || '', //base64图片
	          msg: obj.msg,
	          time: obj.time || Date.now()
	        }

			  //全局的
			  //io.sockets.emit('message',mess);
			  global.logger.info(obj.username + '对' + obj.receive+'说：'+ mess.msg)
			  if(mess.img === ''){
				  //存信息
				  var message = new Message(mess);
				  message.save(function (err, mess) {
					  if (err) {
						  global.logger.error(err)
					  }
					  global.logger.info(mess)
				  });
			  }


			  //根据消息类型回复
			if(mess.type == 4){
				//包括自己再内的群聊
				var msgkey = 'room'+mess.type;
				io.sockets.in(msgkey).emit('message', mess);
			}

			if(mess.type == 5 && mess.img === ''){
				//机器人聊天
				socket.emit("message",mess);
				robot.receive({socket:that,msg:mess});
			}
      });
      

      
      socket.on('login',function (obj) {
        console.log("login",obj);
      });
      
      socket.on('logout',function (obj) {
        try{
          console.log("logout",obj);
        } catch (e) {
          global.logger.error(e)
        }
      });
    
      socket.on('disconnect', function () {
      	var that = this;
      	delete users[that.username];
        global.logger.info(that.username + '下线了')
      });
    });
}


//socket.broadcast.emit('message',data);
module.exports = websocket